import axios from 'axios'
import { message } from 'antd'
import { getToken } from '../util/user-token'
import { ResType } from '../types'

const instance = axios.create({
  timeout: 10 * 1000,
})

// request 请求拦截器：每次请求都带上 token
instance.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Bearer ${getToken()}` // JWT 的固定格式
    return config
  },
  error => Promise.reject(error)
)

// response 响应拦截器：统一处理 errno 和 msg
instance.interceptors.response.use(res => {
  const resData = (res.data || {}) as ResType   // as成ResType类型
  const { errno, data, msg } = resData

  if (errno !== 0) {
    // 错误提示
    if (msg) {
      message.error(msg)
    }

    throw new Error(msg)
  }

  return data as any
})

export default instance